<template>
  <div class="register">
    <div class="registerBox">
      <h2>低代码平台注册</h2>
      <el-form label-width="80px" :model="formData" ref="form" :rules="rules">
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="formData.password"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="邀请码">
          <el-input v-model="formData.invitation_code" />
        </el-form-item>
        <el-form-item label-width="0">
          <el-button type="primary" style="width: 100%" @click="handleRegister(form)">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
export default {
  name: "register"
}
</script>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue"
import {RegisterType} from '@/type/registerType'
import {ElMessage, FormInstance, FormRules} from 'element-plus'
import {userRegister} from '@/api/system'
import {useRouter} from 'vue-router'


const router = useRouter()

const form = ref<FormInstance>()

const formData = reactive<RegisterType>({
  username: "",
  password: "",
  phone: "",
  invitation_code: ""
})

const rules :FormRules<RegisterType> = {
  username: [{
    required: true,
    message: "请输入用户账号",
    trigger: "blur"
  }],
  password: [{
    required: true,
    message: "请输入用户密码",
    trigger: "blur"
  }],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      validator: (_: any, value: string) => {
        return /^1[3456789]\d{9}$/.test(value)
      },
      message: "请输入正确的手机号",
      trigger: "blur"
    }
  ],
}

const handleRegister = (form: FormInstance | undefined) => {
  if (form)
  form.validate((v: boolean) => {
    if (v) {
      userRegister(formData).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.msg)
          router.push({
            name: "login"
          })
        }
      })
    }
  })
}

onMounted( () => {
} )
</script>

<style scoped lang="scss">
.register{
  position: relative;
  width: 100vw;
  height: 100vh;
  .registerBox{
    width: 400px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 16px;
    h2{
      text-align: center;
    }
  }
}
</style>
